package com.elinkway.infinitemovies.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.MalformedInputException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

public class FileUtils {

    public static String SDPATH = Environment.getExternalStorageDirectory()
            + "/Photo_LJ/";

    public static void saveBitmap(Bitmap bm, String picName) {
        try {
            if (!isFileExist("")) {
                File tempf = createSDDir("");
            }
            File f = new File(SDPATH, picName + ".JPEG");
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File createSDDir(String dirName) throws IOException {
        File dir = new File(SDPATH + dirName);
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {

            System.out.println("createSDDir:" + dir.getAbsolutePath());
            System.out.println("createSDDir:" + dir.mkdir());
        }
        return dir;
    }

    public static String getLocalTime() {
        Date date = new Date();//创建一个时间对象，获取到当前的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");//设置时间显示格式
        String str = sdf.format(date);//将当前时间格式化为需要的类型
        return str;
    }

    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        file.isFile();
        return file.exists();
    }

    public static void delFile(String fileName) {
        File file = new File(SDPATH + fileName);
        if (file.isFile()) {
            file.delete();
        }
        file.exists();
    }

    public static void deleteDir() {
        File dir = new File(SDPATH);
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir();
        }
        dir.delete();
    }

    public static boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {

            return false;
        }
        return true;
    }

    private static ImageUploadUtil uploadUtil;
    private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private static final String PREFIX = "--";
    private static final String LINE_END = "\r\n";
    private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private static final String TAG = "ImageUploadUtil";
    private static int readTimeOut = 10 * 1000; // 读取超时
    private static int connectTimeout = 10 * 1000; // 超时时间
    /***
     * 请求使用多长时间
     */
    private static int requestTime = 0;

    private static final String CHARSET = "utf-8"; // 设置编码

    /***
     * 上传成功
     */
    public static final int UPLOAD_SUCCESS_CODE = 1;
    /**
     * 文件不存在
     */
    public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
    /**
     * 服务器出错
     */
    public static final int UPLOAD_SERVER_ERROR_CODE = 3;
    protected static final int WHAT_TO_UPLOAD = 1;
    protected static final int WHAT_UPLOAD_DONE = 2;

    public static void uploadFile(String filePath, String token, String RequestURL,
                           Map<String, String> param) {
        if (filePath == null) {
            sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
            return;
        }
        try {
            File file = new File(filePath);
            uploadFile(file, token, RequestURL, param);
        } catch (Exception e) {
            sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
            e.printStackTrace();
            return;
        }
    }

    public static void uploadFile(final File file, final String token,
                           final String RequestURL, final Map<String, String> param) {
        if (file == null || (!file.exists())) {
            sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
            return;
        }

        Log.i(TAG, "请求的URL=" + RequestURL);
        Log.i(TAG, "请求的fileName=" + file.getName());
        Log.i(TAG, "请求的token=" + token);
        new Thread(new Runnable() { //开启线程上传文件
            @Override
            public void run() {
                toUploadFile(file, token, RequestURL, param);
            }
        }).start();

    }

    public static void toUploadFile(File file, String token, String RequestURL,
                              Map<String, String> param) {
        String result = null;
        requestTime = 0;

        long requestTime = System.currentTimeMillis();
        long responseTime = 0;

        try {
            if (param != null && param.size() > 0) {
                StringBuffer string = new StringBuffer();
                String params = "";
                string.append("?");
                Iterator<String> it = param.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    String value = param.get(key);
                    string.append(key + "=");
                    string.append(value);
                    if (it.hasNext()) {
                        string.append("&");
                    }
                }
                if (!TextUtils.isEmpty(string)) {
                    params = string.toString();
                }
                RequestURL = RequestURL + params;
                LogUtils.e("", "RequestURL is " + RequestURL);
            }
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(readTimeOut);
            conn.setConnectTimeout(connectTimeout);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式n
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + "; boundary=" + BOUNDARY);

            conn.addRequestProperty("k-token", MoviesApplication.getInstance().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE).getString(LoginActivity.TOKEN, ""));
            conn.addRequestProperty("k-uid", MoviesApplication.getInstance().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE).getString(LoginActivity.UID, ""));
            conn.addRequestProperty("k-appid", MoviesHttpApi.PLATFORM_IN_UPGRADE);
            conn.addRequestProperty("k-market", MoviesUtils.getClientChannel());
            conn.addRequestProperty("k-version", MoviesUtils.getClientVersionName());
            conn.addRequestProperty("k-terminal", MoviesHttpApi.PLATTYPE_VAULE);
            conn.addRequestProperty("k-model", MoviesUtils.getDeviceModel());
            conn.addRequestProperty("k-screen", MoviesUtils.getResolution(MoviesApplication.getInstance()));
            conn.addRequestProperty("k-os", "Android " + MoviesUtils.getOSVersion());
            conn.addRequestProperty("k-sdk", MoviesUtils.getMSdk());
            conn.addRequestProperty("k-uuid", MoviesConstant.UUID);
            conn.addRequestProperty("k-dc", MoviesUtils.getmDeviceId());

            /**
             * 当文件不为空，把文件包装并且上传
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());   //getOutputStream()会隐含的进行连接，如同conn.connect();
            StringBuffer sb = null;
            String params = "";

//            /**
//             * 组拼文本类型的参数
//             */
//            if (param != null && param.size() > 0) {
//                Iterator<String> it = param.keySet().iterator();
//                while (it.hasNext()) {
//                    sb = null;
//                    sb = new StringBuffer();
//                    String key = it.next();
//                    String value = param.get(key);
//                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
//                    sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
//                    sb.append(value).append(LINE_END);
//                    params = sb.toString();
//                    Log.i(TAG, key + "=" + params + "##");
//                    dos.write(params.getBytes());
//                }
//            }

            sb = null;
            params = null;
            sb = new StringBuffer();

            /**
             * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
             * filename是文件的名字，包含后缀名的 比如:abc.png
             */
            sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition:form-data; name=\"" + "logFile"
                    + "\"; filename=\"" + "Android_" + MoviesConstant.UUID + "_" + getLocalTime() + "_YSDQ.log" + "\"" + LINE_END);
            sb.append("Content-Type:logFile/log" + LINE_END); // 这里配置的Content-type很重要的 ，用于服务器端辨别文件的类型的
            sb.append(LINE_END);
            params = sb.toString();
            sb = null;

            Log.i(TAG, file.getName() + "=" + params + "##");
            dos.write(params.getBytes());
            /**上传文件*/
            InputStream is = new FileInputStream(file);
            if (onUploadProcessListener != null) {
                onUploadProcessListener.initUpload((int) file.length());
            }
            byte[] bytes = new byte[1024];
            int len = 0;
            int curLen = 0;
            while ((len = is.read(bytes)) != -1) {
                curLen += len;
                dos.write(bytes, 0, len);
                if (onUploadProcessListener != null) {
                    onUploadProcessListener.onUploadProcess(curLen);
                }
            }
            is.close();

            dos.write(LINE_END.getBytes());
            /**请求结束标志*/
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
            int res = conn.getResponseCode();
            responseTime = System.currentTimeMillis();
            FileUtils.requestTime = (int) ((responseTime - requestTime) / 1000);
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                Log.e(TAG, "request success");
                InputStream input = conn.getInputStream();  //实际发送请求的代码段就在这里,本次HTTP请求已结束
                StringBuffer sb1 = new StringBuffer();
                byte[] b = new byte[1024];
                int ss;
                while ((ss = input.read(b)) != -1) {
                    sb1.append(new String(b, "utf-8"));
                }
                result = sb1.toString();
                if (input != null) {
                    input.close();
                }
                Log.e(TAG, "result : " + result);
                sendMessage(UPLOAD_SUCCESS_CODE, result);
            } else {
                Log.e(TAG, "request error");
                sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败：code=" + res);
            }
        } catch (MalformedInputException e) {
            sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败：error=" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败：error=" + e.getMessage());
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 发送上传结果
     *
     * @param responseCode
     * @param responseMessage
     */
    public static void sendMessage(int responseCode, String responseMessage) {
        if (onUploadProcessListener != null) {
            onUploadProcessListener.onUploadDone(responseCode, responseMessage);
        }
    }

    /**
     * 下面是一个自定义的回调函数，用到回调上传文件是否完成
     *
     * @author shimingzheng
     */
    public interface OnUploadProcessListener {
        /**
         * 上传响应
         *
         * @param responseCode
         * @param message
         */
        void onUploadDone(int responseCode, String message);

        /**
         * 上传中
         *
         * @param uploadSize
         */
        void onUploadProcess(int uploadSize);

        /**
         * 准备上传
         *
         * @param fileSize
         */
        void initUpload(int fileSize);
    }

    public static OnUploadProcessListener onUploadProcessListener = null;

    public static void setOnUploadProcessListener(
            OnUploadProcessListener onUploadProcessListener) {
            FileUtils.onUploadProcessListener = onUploadProcessListener;
    }

    public int getReadTimeOut() {
        return readTimeOut;
    }

    public void setReadTimeOut(int readTimeOut) {
        this.readTimeOut = readTimeOut;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    /**
     * 获取上传使用的时间
     *
     * @return
     */
    public static int getRequestTime() {
        return requestTime;
    }

    public static interface uploadProcessListener {

    }

    /**
     * 上传app日志
     */
    public static void uploadAppLog() {
        Map<String, String> para = new HashMap<>();
        String url = "/sdcard/" + LogCat.LOG_FILE_NAME;
        String ts = System.currentTimeMillis() + "";
        para.put("ts", ts);
        para.put("token", MD5Utils.md5(ts + "ysdq_log_upload_secret_2016"));
        FileUtils.setOnUploadProcessListener(new FileUtils.OnUploadProcessListener() {
            @Override
            public void onUploadDone(int responseCode, String message) {
                String imgUrl = "";
                String code = "";
                String msg = "";
                try {
                    JSONObject result = new JSONObject(message);
                    if(result != null){
                        code = result.optString("code");
                        msg = result.optString("msg");
                        if ("200".equals(code)) {
                            LogUtils.e("slideMenuFragment", "Log upload success");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onUploadProcess(int uploadSize) {

            }

            @Override
            public void initUpload(int fileSize) {

            }
        });
        FileUtils.uploadFile(url, "", "http://106.120.179.42:9001/wxticket/log/upload", para);
    }

}
